package com.moleq.mginventory.activities;


import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

import com.moleq.base.MoleQBaseActivity;
import com.moleq.device.BaseScanner;
import com.moleq.device.DeviceManager;
import com.moleq.device.DeviceSettingService;
import com.moleq.device.IDeviceEvent;
import com.moleq.device.ScannerSetting;
import com.moleq.dialog.MessageBox;
import com.moleq.dialog.MessageDialog;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.logic.PosPrinter;
import com.moleq.logic.UPC;
import com.moleq.mgpos.activities.R;
import com.moleq.models.GlobalInfo;

import com.moleq.network.Constant;
import com.moleq.network.InventoryReport;
import com.moleq.network.InventoryReportCreator;
import com.moleq.network.ReportCreator;
import com.moleq.service.ServiceManager;
import com.moleq.util.MoleQUtil;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class InventoryActivity extends MoleQBaseActivity {
	
	private TextView tv_content;
	private EditText et_upc;
	private Button btn_search,btn_print,btn_exit;
	private InventoryReportCreator creator = null;
	public HashMap<String, InventoryReport> respots = new HashMap<String, InventoryReport>();
	private DeviceSettingService mSettingService;
	private DeviceManager mDeviceManager;
	private LinearLayout ll_top;
	private CheckBox cb_rt;
	private boolean isNormalize = false;
	private static ProgressDialog mProgressDlg;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_inventory);
		
		creator = new InventoryReportCreator(GlobalInfo.getInstance().ShareItyContext,GlobalInfo.getInstance().ShareContext);
		
		FindControlId();
		btn_search.setOnClickListener(onClickListener);
		btn_print.setOnClickListener(onClickListener);
		btn_exit.setOnClickListener(onClickListener);
		ll_top.setOnClickListener(onClickListener);
		initReports();
		
		 // =========== setup scanner =================
		mDeviceManager = DeviceManager.getInstance();
		mSettingService = ServiceManager.getInstance().mDeviceSettingService;
		
		List<ScannerSetting> scannerSettings = mSettingService
				.getScannerSettings();

		// check scanner
		int iScannerCount = scannerSettings.size();
		for (int i = 0; i < iScannerCount; i++) {
			int iPort = scannerSettings.get(i).getPort();
			for (int j = i + 1; j < iScannerCount; j++) {
				if (iPort == scannerSettings.get(j).getPort()) {
					// Toast.makeText(PriceSettingActivity.this,
					// " Scanner setup error. Please check.",
					// Toast.LENGTH_LONG).show();
					MessageBox.show(this, " Scanner setup error. Please check.");
					finish();
				}

			}
		}

		for (int i = 0; i < scannerSettings.size(); i++) {
			BaseScanner baseScanner = new BaseScanner();
			baseScanner.setScannerSetting(scannerSettings.get(i));
			mDeviceManager.addScanner(baseScanner);
		}

		// open scanner
		for (int i = 0; i < mDeviceManager.scanners.size(); i++) {
			mDeviceManager.scanners.get(i).onConnect();
			mDeviceManager.scanners.get(i).setCallbackEvent(this);
			mDeviceManager.scanners.get(i).onEnableScanner();
		}

		// ============================================
		
		mProgressDlg = new ProgressDialog(InventoryActivity.this);
		mProgressDlg.setTitle("");
		mProgressDlg.setMessage("Please wait......");
		mProgressDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//		mProgressDlg.setIcon(R.drawable.icon);//设置图标  
//		mProgressDlg.setMessage("这是一个圆形进度条");  
		mProgressDlg.setIndeterminate(false);//设置进度条是否为不明确  
		mProgressDlg.setCancelable(true);//设置进度条是否可以按退回键取消  
		mProgressDlg.setButton("Cancel", new DialogInterface.OnClickListener(){  

              @Override  
              public void onClick(DialogInterface dialog, int which) {  
                  dialog.cancel();  
                    
              }  
                
          }); 
	}
	
	public void dispose() {
		// disable all scanner
		mDeviceManager.disposeScanner();

		// disabel scale
		mDeviceManager.disposeScale();

		if (mDeviceManager.screen != null && mDeviceManager.screen.isConnected()) {
			mDeviceManager.screen.onDisconnect();
		}

		mDeviceManager.resetALLDevices();
			
	}
	
	public void initReports() {
		respots.put(Constant.INVENTORY, new InventoryReport("Inventory"));
		respots.put(Constant.RECEIVING_INQUIRY, new InventoryReport("Receiving Inquiry"));
	}


	private void FindControlId() {
		tv_content = (TextView) findViewById(R.id.tv_content);
		et_upc = (EditText) findViewById(R.id.et_upc);
		btn_search = (Button) findViewById(R.id.btn_search);
		btn_print = (Button) findViewById(R.id.btn_print);
		btn_exit = (Button) findViewById(R.id.btn_exit);
		ll_top = (LinearLayout)findViewById(R.id.ll_top);
		cb_rt = (CheckBox)findViewById(R.id.cb_rt);
	}
	
	OnClickListener onClickListener = new OnClickListener() {
		
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.btn_search:
				Search(et_upc.getText().toString());
				
				break;
			case R.id.btn_print:
				String context = tv_content.getText().toString();
				if(context.trim().equals("")) return;
				PosPrinter printer = new PosPrinter();
				if(!printer.isBusy()){
					printer.onConnect();
					printer.print(context);
					printer.cutPaper();
					printer.onDisconnect();
				}
				break;
			case R.id.btn_exit:
				MessageBox.show(InventoryActivity.this,InventoryActivity.this.getResources().
						getString(R.string.msg_exit_program).toString(), onClickMessageListener, MessageDialog.MESSAGE_BOX_YES_NO);
				break;
			case R.id.ll_top:
				Keyboard();
				break;
			}
		}
	};
	
	public void  Search(String code){
		tv_content.setText("");
		Keyboard();
		if(!validation())return;
		
		et_upc.setText("");
		UPC upc = new UPC(code, UPC.INPUT_BY_MANUAL,isNormalize );
	
		String ls_content = "";
		
		InventoryReport rpt = respots.get(Constant.INVENTORY);
		rpt.reset();
		ConvertLoaclData(creator.getInventoryRptByUpc(upc.code));
		String content = "";
		content = rpt.toPrintInventory();
		if (content.equals("")) {
			MessageBox.show(InventoryActivity.this, "Data not Found.");
			tv_content.setText("");
			return;
		}
		
		mProgressDlg.show();
		String singleRptContent = "";
		singleRptContent += rpt.getReportName("") + content ;
		if (cb_rt.isChecked()) {
			singleRptContent += "\n\n===============================================\n";
			rpt = respots.get(Constant.RECEIVING_INQUIRY);
			rpt.reset();
			ConvertLoaclData(creator.getInventoryReceiving(upc.code));
			singleRptContent += rpt.getReportDetailName("Receiving")+ rpt.toPrintReport()+rpt.getFooter("",false)+"\n";
			
			rpt = respots.get(Constant.INVENTORY);
			rpt.reset();
			ConvertLoaclData(creator.getInventoryRptDetailByUpc(upc.code));
			singleRptContent += rpt.getReportDetailName("Item Sales")+ rpt.toPrintReport()+rpt.getFooter("",false);
			singleRptContent +="===============================================";
		}
		
		mProgressDlg.cancel();
		ls_content += singleRptContent;
		
		tv_content.setText(ls_content);
		
	}
	
	 public boolean validation(){
			
			if (et_upc.getText().toString().trim().equals("")) {
				
				MessageBox.show(this, "UPC can not be empty.");
				return false;
			}
	    	
	    	return true;
	    	
	    }
	 
	 public void Keyboard() {
			InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			inputMethodManager.hideSoftInputFromWindow(InventoryActivity.this
					.getCurrentFocus().getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
		}
	 
	private OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {

		public void onClickYes() {
			mProgressDlg.dismiss();
			dispose();
			finish();
		}

		public void onClickNo() {
//			mMessageDialog.dismiss();
		}

		public void onClickOK() {
//			mMessageDialog.dismiss();
		}
	};

	@Override
	public void onErrorEvent(String res) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onScannerEvent(String res) {
		// TODO Auto-generated method stub
		et_upc.setText(res);
		Search(res);
	}

	@Override
	public void onWeightEvent(int res) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTimeOutEvent() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onDataEvent(Object obj) {
		// TODO Auto-generated method stub
		
	}

	
	public void onEventResponse(Object obj) {
		// TODO Auto-generated method stub
		
	}
	
	public void ConvertLoaclData(String reportData) {

		String temp[] = reportData.split("\\|");
		String reportName = temp[0];
		for (int i = 1; i < temp.length; i++) {

			String item = temp[i];
			List<String> newStrings = MoleQUtil.parseSqlRecord(item.substring(1, item.length() - 1));

			String[] line = new String[newStrings.size()];

			for (int j = 0; j < newStrings.size(); j++) {
				String ls = newStrings.get(j);
//				String ls2 = ls.substring(0, 1);
//				if (ls2.equals("'")) {
//					ls = ls.substring(1, ls.length() - 1);
//				}
				line[j] = ls;
			}

			InventoryReport rpt = respots.get(reportName);
			rpt.sum(line);
		}
	}
	
}
